<template>
  <div class="container">
    <el-header style="height: 60px; padding: 0 20px; background: white; box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);">
      <div style="display: flex; justify-content: space-between; align-items: center; height: 100%;">
        <h2>个人博客系统</h2>
        <div>
          <el-button link @click="$router.push('/')">返回首页</el-button>
          <template v-if="!isLoggedIn">
            <el-button link @click="$router.push('/login')">登录</el-button>
            <el-button link @click="$router.push('/register')">注册</el-button>
          </template>
          <template v-else>
            <el-button link @click="$router.push('/backend')">后台管理</el-button>
            <el-button link @click="handleLogout">退出</el-button>
          </template>
        </div>
      </div>
    </el-header>

    <div class="article-detail-container">
      <div class="article-content">
        <h1>{{ articleData.title || '加载中...' }}</h1>
        <div class="article-meta">
          <span>作者：{{ articleData.nickname || '未知' }}</span>
          <span>发布时间：{{ formatDate(articleData.createTime) }}</span>
          <span>浏览量：{{ articleData.viewCount || 0 }}</span>
        </div>
        <div class="article-body" v-html="articleData.content || '内容加载中...'"></div>
      </div>

      <div class="comment-section">
        <div class="comment-header-title">
          <el-divider>
            <el-icon><ChatDotRound /></el-icon>
            <span class="comment-title">评论区 ({{ total }})</span>
          </el-divider>
        </div>
        
        <div v-if="isLoggedIn" class="comment-form">
          <div class="comment-form-header">
            <el-avatar :size="40" :src="userAvatar">{{ getUserInitial() }}</el-avatar>
            <span class="current-user">{{ username }}</span>
          </div>
          <el-input
            v-model="commentContent"
            type="textarea"
            :rows="3"
            placeholder="写下你的评论..."
            class="comment-textarea"
          />
          <div class="comment-form-footer">
            <el-button type="primary" :disabled="!commentContent.trim()" @click="submitComment" round>
              <el-icon><Position /></el-icon> 发表评论
            </el-button>
          </div>
        </div>
        <div v-else class="login-tip">
          <el-alert
            title="请先登录后再发表评论"
            type="info"
            :closable="false"
            center
            show-icon>
            <template #default>
              <el-button type="primary" size="small" @click="$router.push('/login')" round>
                立即登录
              </el-button>
            </template>
          </el-alert>
        </div>

        <div class="comment-list">
          <template v-if="comments.length > 0">
            <div v-for="comment in comments" :key="comment.id" class="comment-item">
              <div class="comment-item-avatar">
                <el-avatar :size="40" :src="getAvatarUrl(comment.nickname)">{{ getInitial(comment.nickname) }}</el-avatar>
              </div>
              <div class="comment-item-content">
                <div class="comment-item-header">
                  <span class="comment-author">{{ comment.nickname }}</span>
                  <el-tag size="small" effect="plain" class="comment-time">
                    <el-icon><Timer /></el-icon>
                    {{ formatDate(comment.createTime) }}
                  </el-tag>
                </div>
                <div class="comment-text">{{ comment.content }}</div>
              </div>
            </div>
          </template>
          <el-empty v-else description="暂无评论，快来发表第一条评论吧！" :image-size="100"></el-empty>
        </div>

        <div v-if="total > pageSize" class="pagination-container">
          <el-pagination
            :current-page="currentPage"
            :page-size="pageSize"
            :total="total"
            :page-sizes="[10, 20, 30, 50]"
            background
            layout="total, sizes, prev, pager, next"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { article, comment } from '@/api'
import { ChatDotRound, Position, Timer } from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter()

// 安全地获取localStorage
const getLocalStorage = (key) => {
  try {
    return localStorage.getItem(key)
  } catch (e) {
    console.error('无法访问localStorage:', e)
    return null
  }
}

// 安全地设置localStorage
const setLocalStorage = (key, value) => {
  try {
    localStorage.setItem(key, value)
    return true
  } catch (e) {
    console.error('无法设置localStorage:', e)
    return false
  }
}

// 安全地移除localStorage
const removeLocalStorage = (key) => {
  try {
    localStorage.removeItem(key)
    return true
  } catch (e) {
    console.error('无法移除localStorage:', e)
    return false
  }
}

const isLoggedIn = computed(() => !!getLocalStorage('token'))
const username = computed(() => getLocalStorage('username') || '游客')

const articleData = ref({})
const comments = ref([])
const commentContent = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const userAvatar = ref('')

const loadArticle = async () => {
  try {
    const res = await article.getById(route.params.id)
    if (res) {
      articleData.value = res
    } else {
      ElMessage.error('文章数据加载失败')
    }
  } catch (error) {
    console.error(error)
    ElMessage.error('文章加载失败')
  }
}

const loadComments = async () => {
  try {
    const res = await comment.getByArticle(route.params.id, {
      current: currentPage.value,
      size: pageSize.value
    })
    if (res && res.records) {
      comments.value = res.records
      total.value = res.total || 0
    }
  } catch (error) {
    console.error(error)
    ElMessage.error('评论加载失败')
  }
}

const submitComment = async () => {
  if (!isLoggedIn.value) {
    ElMessage.warning('请先登录后再评论')
    router.push('/login')
    return
  }

  if (!commentContent.value.trim()) {
    ElMessage.warning('请输入评论内容')
    return
  }

  try {
    await comment.create({
      articleId: route.params.id,
      content: commentContent.value
    })
    ElMessage.success('评论发表成功')
    commentContent.value = ''
    loadComments()
  } catch (error) {
    console.error(error)
    ElMessage.error('评论发表失败')
  }
}

const handleSizeChange = (val) => {
  pageSize.value = val
  loadComments()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  loadComments()
}

const handleLogout = () => {
  removeLocalStorage('token')
  removeLocalStorage('username')
  ElMessage.success('退出成功')
  router.push('/login')
}

const formatDate = (date) => {
  if (!date) return '未知时间'
  return new Date(date).toLocaleString()
}

const getAvatarUrl = (nickname) => {
  // 这里可以根据用户名生成不同的头像颜色或图片
  return ''
}

const getInitial = (name) => {
  return name ? name.charAt(0).toUpperCase() : '?'
}

const getUserInitial = () => {
  return username.value.charAt(0).toUpperCase()
}

onMounted(() => {
  loadArticle()
  loadComments()
})
</script>

<style scoped>
.article-detail-container {
  max-width: 1200px;
  margin: 20px auto;
  padding: 0 20px;
}

.article-content {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.article-meta {
  color: #666;
  margin: 10px 0;
}

.article-meta span {
  margin-right: 20px;
}

.article-body {
  margin-top: 20px;
  line-height: 1.8;
}

.comment-section {
  margin-top: 30px;
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.comment-header-title {
  margin-bottom: 20px;
}

.comment-title {
  font-size: 18px;
  font-weight: bold;
  margin-left: 8px;
}

.comment-form {
  margin-bottom: 30px;
  background-color: #f9f9f9;
  border-radius: 8px;
  padding: 20px;
}

.comment-form-header {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.current-user {
  margin-left: 10px;
  font-weight: bold;
}

.comment-textarea {
  margin-bottom: 10px;
}

.comment-form-footer {
  display: flex;
  justify-content: flex-end;
}

.login-tip {
  margin: 30px 0;
}

.comment-list {
  margin-top: 30px;
}

.comment-item {
  display: flex;
  padding: 15px;
  margin-bottom: 15px;
  border-radius: 8px;
  background-color: #f9f9f9;
  transition: all 0.3s ease;
}

.comment-item:hover {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.comment-item-avatar {
  margin-right: 15px;
}

.comment-item-content {
  flex: 1;
}

.comment-item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.comment-author {
  font-weight: bold;
  font-size: 16px;
  color: #409EFF;
}

.comment-time {
  color: #999;
  font-size: 12px;
}

.comment-text {
  color: #333;
  line-height: 1.6;
  padding: 10px 0;
  white-space: pre-wrap;
}

.pagination-container {
  margin-top: 30px;
  display: flex;
  justify-content: center;
}
</style> 